<template>
  <div class="department-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
          >
            导入
          </el-button>
          <el-button size="small" type="danger" @click="exportDate">
            导出
          </el-button>
          <el-button size="small" type="primary" @click="showDialog = true">
            新增员工
          </el-button>
        </template>
      </page-tools>

      <el-card v-loading="loading">
        <el-table :data="list" style="width: 100%" border="">
          <el-table-column prop="id" label="序号" sortable="" type="index">
          </el-table-column>
          <el-table-column prop="username" label="姓名" sortable="">
          </el-table-column>

          <!-- 放置员工头像 -->
          <el-table-column label="头像" align="center">
            <template v-slot="{ row }">
              <img
                v-imagerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                  cursor: pointer;
                "
                @click="showQrCode(row.staffPhoto)"
              />
            </template>
          </el-table-column>

          <el-table-column prop="workNumber" label="工号" sortable="">
          </el-table-column>
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatEmployment"
          >
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" sortable="">
          </el-table-column>
          <!-- 作用域插槽格式化时间 -->
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template v-slot="{ row }">
              <el-switch :value="row.enableState === 1 ? true : false">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="操作" width="280" fixed="right">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">
                角色
              </el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            :current-page="page.page"
            @current-change="changePage"
          >
          </el-pagination>
        </el-row>
      </el-card>

      <add-employee :show-dialog.sync="showDialog" />
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas"></canvas>
        </el-row>
      </el-dialog>

      <assign-role
        ref="assignRole"
        :show-role-dialog.sync="showRoleDialog"
        :user-id="userId"
      />
    </div>
  </div>
</template>

 <script>
import AssignRole from './components/assign-role.vue'
import { formatDate } from '@/filters'
import addEmployee from './components/add-employee.vue'
import EmployeeEnum from '@/api/constant/employees' // 引入枚举对象
import { getEmployeesList, delEmployee } from '@/api/employees'
import QrCode from 'qrcode'
export default {
  components: {
    addEmployee,
    AssignRole
  },

  data () {
    return {
      userId: '',
      showRoleDialog: false,
      showCodeDialog: false, // 显示二维码弹窗
      showDialog: false,
      value: true,
      loading: false,
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      }
    }
  },

  created () {
    this.getEmployeesList()
  },

  methods: {
    // 查看角色
    async editRole (id) {
      await this.$refs.assignRole.getUserDetailById(id)
      this.userId = id
      this.showRoleDialog = true
    },

    // 图片生成二维码
    showQrCode (url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该员工未上传头像')
      }
    },

    // 导出excel
    exportDate () {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeesList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows)
        const multiHeader = [['手机号', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader,
          merges
        })
      })
    },

    // 将表头数据和数据进行对应
    formatJson (headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // 格式化时间
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },

    // 删除员工
    async delEmployee (id) {
      try {
        await this.$confirm('确认删除该员工吗？')
        await delEmployee(id)
        this.getEmployeesList()
        this.$message.success('操作成功')
      } catch (error) {
        console.log(error)
      }
    },

    // 格式化聘用形式,cellValue是当前行的值,row是当前行的所有数据，
    formatEmployment (row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },

    // 翻页
    changePage (newPage) {
      this.page.page = newPage
      this.getEmployeesList()
    },

    // 获取员工列表
    async getEmployeesList () {
      this.loading = true
      const { rows, total } = await getEmployeesList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    }
  }
}
  </script>

<style>
</style>
